package ltk.servlet;


import hezi.common.RequestParameters;
import hezi.core.Forum;
import hezi.helper.ForumIdComparator;
import hezi.helper.ForumLastscantimeComparator;
import hezi.helper.ForumNewImageCountComparator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;

import dz.common.PropTool;

public class IndexServlet extends BaseServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.doGet(request, response);
		
		sortForumList(request);
		initGroupAndSiteNameList();
		
				
		Template t = ve.getTemplate("index.html");
		
		context.put("proptool",new PropTool());
		context.put("noScaninProcess", !ScanServlet.isInScanProcess());
		context.put("totalNewImageCount",Forum.totalNewImageCount);
		
		SettingServlet.fillContext();
		
		writeout(t);
	}

	
	private void initGroupAndSiteNameList() {
		List<String> sitenamelist = new ArrayList<String>();
		List<String> groupnamelist = new ArrayList<String>();
		for(Forum forum : Forum.getForumList()){
			String groups = forum.getGroups();
			for(String groupname : groups.split(" ")){
				if(groupnamelist.contains(groupname)){
					
				}
				else{
					groupnamelist.add(groupname);
				}
			}
			
			String sitename = forum.getSite().getSitename();
			if(sitenamelist.contains(sitename)){
				
			}
			else{
				sitenamelist.add(sitename);
			}
		}
		Collections.sort(groupnamelist);
		Collections.sort(sitenamelist);
		context.put("groupnamelist",groupnamelist);
		context.put("sitenamelist", sitenamelist);
	}

	private void sortForumList(HttpServletRequest request) {
		String orderby = RequestParameters.getParameter(request, "orderby");
				
		if(orderby.endsWith("forumid")){
			Collections.sort(Forum.getForumList(),new ForumIdComparator());
		}
		else if(orderby.endsWith("lastscantime")){
			Collections.sort(Forum.getForumList(),new ForumLastscantimeComparator());
		}
		else if(orderby.endsWith("newimagecount")){
			Collections.sort(Forum.getForumList(),new ForumNewImageCountComparator());
		}
		else{
			Collections.sort(Forum.getForumList(),new ForumNewImageCountComparator());
		}
		
		context.put("allforum",Forum.getForumList());
	}
}
